package com.xbongbong.pro.service.stage;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.StageProcessEntity;
import com.xbongbong.paas.enums.EnableEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.model.StageProcessModel;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 阶段、版本相关公用查询方法
 * @author zcp
 * @version v1.0
 * @since v1.0
 */
@Component
public abstract class AbstractStageFindService {
    @Resource
    protected CommonHelp commonHelp;
    @Resource
    private StageProcessModel stageProcessModel;

    /**
     * 获取当前启用的流程版本
     * 如果全部未启用，则获取最后一个创建的版本
     * @param corpid
     * @param formId 每个form内只有1个enable的版本，代表当前版本
     * @return com.xbongbong.paas.domain.entity.StageProcessEntity
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    public StageProcessEntity getNowProcess(String corpid, Long formId) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, 0);
        param.put(StringConstant.FORM_ID, formId);
        param.put(ParameterConstant.ENABLE, EnableEnum.OPEN.getCode());
        param.put(ParameterConstant.ORDER_BY_STR, " priority " + SortOrder.ASC);
        param.put(ParameterConstant.START, BasicConstant.ZERO);
        param.put(ParameterConstant.PAGE_NUM, BasicConstant.ONE);
        List<StageProcessEntity> stageProcessEntityList = stageProcessModel.findEntitys(param);
        if (CollectionUtils.isEmpty(stageProcessEntityList)) {
            //没有启用的，则按照创建时间降序获取第一个
            param.remove(ParameterConstant.ENABLE);
            param.put(ParameterConstant.ORDER_BY_STR, " add_time " + SortOrder.DESC);
            stageProcessEntityList = stageProcessModel.findEntitys(param);
        }
        if (CollectionUtils.isNotEmpty(stageProcessEntityList)) {
            return stageProcessEntityList.get(0);
        }
        return null;
    }

    /**
     * 获取当前启用的流程版本的id
     * 如果全部未启用，则获取最后一个创建的版本
     * @param corpid
     * @param formId 每个form内只有1个enable的版本，代表当前版本
     * @return java.lang.Long
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    public Long getNowProcessId(String corpid, Long formId){
        StageProcessEntity stageProcessEntity = getNowProcess(corpid, formId);
        if (Objects.nonNull(stageProcessEntity)) {
            return stageProcessEntity.getId();
        }
        return null;
    }
}
